<template>
  <el-dialog v-model="dialogVisible" title="预案模板管理" width="1200px" :close-on-click-modal="false">
    <div class="template-manage">
      <!-- 操作栏 -->
      <div class="action-bar">
        <div class="left-actions">
          <el-button type="primary" @click="showCreateTemplateDialog">
            <el-icon>
              <Plus />
            </el-icon>
            创建模板
          </el-button>
          <el-button type="success" @click="importTemplate">
            <el-icon>
              <Upload />
            </el-icon>
            导入模板
          </el-button>
          <el-button type="warning" @click="exportSelectedTemplates" :disabled="selectedTemplates.length === 0">
            <el-icon>
              <Download />
            </el-icon>
            导出模板
          </el-button>
          <el-button type="danger" @click="deleteSelectedTemplates" :disabled="selectedTemplates.length === 0">
            <el-icon>
              <Delete />
            </el-icon>
            批量删除
          </el-button>
        </div>

        <div class="right-actions">
          <el-input v-model="searchKeyword" placeholder="搜索模板名称、类型或描述" style="width: 300px" clearable>
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="info" @click="refreshTemplates">
            <el-icon>
              <Refresh />
            </el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 模板分类 -->
      <div class="template-categories">
        <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
          <el-tab-pane label="全部模板" name="all">
            <span slot="label">
              <el-icon>
                <Document />
              </el-icon>
              全部模板 ({{ totalTemplates }})
            </span>
          </el-tab-pane>
          <el-tab-pane label="防洪预案" name="flood">
            <span slot="label">
              <el-icon>
                <Umbrella />
              </el-icon>
              防洪预案 ({{ getTemplateCountByType('flood') }})
            </span>
          </el-tab-pane>
          <el-tab-pane label="抗旱预案" name="drought">
            <span slot="label">
              <el-icon>
                <Sunny />
              </el-icon>
              抗旱预案 ({{ getTemplateCountByType('drought') }})
            </span>
          </el-tab-pane>
          <el-tab-pane label="供水预案" name="water-supply">
            <span slot="label">
              <el-icon>
                <Setting />
              </el-icon>
              供水预案 ({{ getTemplateCountByType('water-supply') }})
            </span>
          </el-tab-pane>
          <el-tab-pane label="安全预案" name="safety">
            <span slot="label">
              <el-icon>
                <Setting />
              </el-icon>
              安全预案 ({{ getTemplateCountByType('safety') }})
            </span>
          </el-tab-pane>
          <el-tab-pane label="自定义" name="custom">
            <span slot="label">
              <el-icon>
                <Setting />
              </el-icon>
              自定义 ({{ getTemplateCountByType('custom') }})
            </span>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 模板列表 -->
      <div class="template-list">
        <el-table :data="filteredTemplates" stripe @selection-change="handleSelectionChange" row-key="id">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="模板名称" min-width="200">
            <template #default="{ row }">
              <div class="template-name">
                <el-icon class="template-icon">
                  <component :is="getTemplateIcon(row.type)" />
                </el-icon>
                <span>{{ row.name }}</span>
                <el-tag v-if="row.isOfficial" type="success" size="small" style="margin-left: 8px">
                  官方
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="模板类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)" size="small">
                {{ getTypeText(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="version" label="版本" width="100">
            <template #default="{ row }">
              <el-tag type="info" size="small">{{ row.version }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="usageCount" label="使用次数" width="100">
            <template #default="{ row }">
              <span class="usage-count">{{ row.usageCount }} 次</span>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建者" width="120" />
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="模板描述" min-width="200">
            <template #default="{ row }">
              <span class="description-text">{{ row.description || '暂无描述' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="270" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="previewTemplate(row)">
                预览
              </el-button>
              <el-button type="success" size="small" @click="useTemplate(row)">
                使用
              </el-button>
              <el-button type="warning" size="small" @click="editTemplate(row)" :disabled="row.isOfficial">
                编辑
              </el-button>
              <el-button type="info" size="small" @click="copyTemplate(row)">
                复制
              </el-button>
              <el-button type="danger" size="small" @click="deleteTemplate(row)" :disabled="row.isOfficial">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalFilteredTemplates"
            :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 创建/编辑模板对话框 -->
    <el-dialog v-model="templateFormVisible" :title="isEditMode ? '编辑模板' : '创建模板'" width="800px"
      :close-on-click-modal="false" append-to-body>
      <el-form ref="templateFormRef" :model="templateForm" :rules="templateFormRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="type">
              <el-select v-model="templateForm.type" placeholder="请选择模板类型" style="width: 100%">
                <el-option label="防洪预案" value="flood" />
                <el-option label="抗旱预案" value="drought" />
                <el-option label="供水预案" value="water-supply" />
                <el-option label="安全预案" value="safety" />
                <el-option label="自定义" value="custom" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="templateForm.version" placeholder="如：v1.0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="适用范围" prop="scope">
              <el-select v-model="templateForm.scope" placeholder="请选择适用范围" style="width: 100%">
                <el-option label="全局" value="global" />
                <el-option label="区域" value="regional" />
                <el-option label="项目" value="project" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="模板描述" prop="description">
          <el-input v-model="templateForm.description" type="textarea" :rows="3" placeholder="请输入模板描述" />
        </el-form-item>

        <el-form-item label="模板标签">
          <el-tag v-for="tag in templateForm.tags" :key="tag" closable @close="removeTag(tag)"
            style="margin-right: 8px">
            {{ tag }}
          </el-tag>
          <el-input v-if="tagInputVisible" ref="tagInputRef" v-model="tagInputValue" size="small" style="width: 100px"
            @keyup.enter="addTag" @blur="addTag" />
          <el-button v-else size="small" @click="showTagInput">+ 添加标签</el-button>
        </el-form-item>

        <el-form-item label="模板内容" prop="content">
          <div class="template-content-editor">
            <el-tabs v-model="contentTab" type="border-card">
              <el-tab-pane label="基本信息" name="basic">
                <el-form label-width="120px">
                  <el-form-item label="预案名称模板">
                    <el-input v-model="templateForm.content.basic.nameTemplate" placeholder="如：{区域}防洪应急预案" />
                  </el-form-item>
                  <el-form-item label="优先级">
                    <el-select v-model="templateForm.content.basic.priority" style="width: 100%">
                      <el-option label="低" value="low" />
                      <el-option label="中" value="medium" />
                      <el-option label="高" value="high" />
                      <el-option label="紧急" value="urgent" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="描述模板">
                    <el-input v-model="templateForm.content.basic.descriptionTemplate" type="textarea" :rows="3"
                      placeholder="预案描述模板" />
                  </el-form-item>
                </el-form>
              </el-tab-pane>

              <el-tab-pane label="触发条件" name="triggers">
                <div class="trigger-conditions">
                  <el-button type="primary" size="small" @click="addTriggerCondition">
                    添加触发条件
                  </el-button>
                  <div v-for="(condition, index) in templateForm.content.triggers" :key="index" class="condition-item">
                    <el-card shadow="never">
                      <el-row :gutter="20">
                        <el-col :span="6">
                          <el-select v-model="condition.parameter" placeholder="监测参数">
                            <el-option label="水位" value="water-level" />
                            <el-option label="流量" value="flow" />
                            <el-option label="降雨量" value="rainfall" />
                            <el-option label="水质" value="water-quality" />
                          </el-select>
                        </el-col>
                        <el-col :span="4">
                          <el-select v-model="condition.operator" placeholder="操作符">
                            <el-option label=">" value="gt" />
                            <el-option label=">=" value="gte" />
                            <el-option label="<" value="lt" />
                            <el-option label="<=" value="lte" />
                            <el-option label="=" value="eq" />
                          </el-select>
                        </el-col>
                        <el-col :span="6">
                          <el-input v-model="condition.value" placeholder="阈值" />
                        </el-col>
                        <el-col :span="4">
                          <el-input v-model="condition.unit" placeholder="单位" />
                        </el-col>
                        <el-col :span="4">
                          <el-button type="danger" size="small" @click="removeTriggerCondition(index)">
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                    </el-card>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="执行步骤" name="steps">
                <div class="execution-steps">
                  <el-button type="primary" size="small" @click="addExecutionStep">
                    添加执行步骤
                  </el-button>
                  <div v-for="(step, index) in templateForm.content.steps" :key="index" class="step-item">
                    <el-card shadow="never">
                      <el-row :gutter="20">
                        <el-col :span="8">
                          <el-input v-model="step.name" placeholder="步骤名称" />
                        </el-col>
                        <el-col :span="6">
                          <el-select v-model="step.type" placeholder="步骤类型">
                            <el-option label="通知" value="notification" />
                            <el-option label="操作" value="operation" />
                            <el-option label="检查" value="check" />
                            <el-option label="等待" value="wait" />
                          </el-select>
                        </el-col>
                        <el-col :span="6">
                          <el-input v-model="step.responsible" placeholder="负责人" />
                        </el-col>
                        <el-col :span="4">
                          <el-button type="danger" size="small" @click="removeExecutionStep(index)">
                            删除
                          </el-button>
                        </el-col>
                      </el-row>
                      <el-row style="margin-top: 10px">
                        <el-col :span="24">
                          <el-input v-model="step.description" type="textarea" :rows="2" placeholder="步骤描述" />
                        </el-col>
                      </el-row>
                    </el-card>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="人员配置" name="personnel">
                <el-form label-width="120px">
                  <el-form-item label="通知人员">
                    <el-select v-model="templateForm.content.personnel.notification" multiple placeholder="选择通知人员"
                      style="width: 100%">
                      <el-option label="值班员" value="duty-officer" />
                      <el-option label="调度员" value="dispatcher" />
                      <el-option label="技术员" value="technician" />
                      <el-option label="管理员" value="manager" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="执行人员">
                    <el-select v-model="templateForm.content.personnel.execution" multiple placeholder="选择执行人员"
                      style="width: 100%">
                      <el-option label="操作员" value="operator" />
                      <el-option label="维护员" value="maintainer" />
                      <el-option label="安全员" value="safety-officer" />
                      <el-option label="应急队" value="emergency-team" />
                    </el-select>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="templateFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveTemplate" :loading="saveTemplateLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模板预览对话框 -->
    <el-dialog v-model="previewVisible" title="模板预览" width="1000px" :close-on-click-modal="false" append-to-body>
      <div v-if="previewTemplate" class="template-preview">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="模板名称">{{ previewTemplate.name }}</el-descriptions-item>
          <el-descriptions-item label="模板类型">{{ getTypeText(previewTemplate.type) }}</el-descriptions-item>
          <el-descriptions-item label="版本">{{ previewTemplate.version }}</el-descriptions-item>
          <el-descriptions-item label="创建者">{{ previewTemplate.creator }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDateTime(previewTemplate.createTime)
            }}</el-descriptions-item>
          <el-descriptions-item label="模板描述" :span="2">{{ previewTemplate.description }}</el-descriptions-item>
        </el-descriptions>

        <div class="preview-content">
          <h4>模板内容预览</h4>
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <p><strong>预案名称模板：</strong>{{ previewTemplate.content?.basic?.nameTemplate || '未设置' }}</p>
              <p><strong>优先级：</strong>{{ previewTemplate.content?.basic?.priority || '未设置' }}</p>
              <p><strong>描述模板：</strong>{{ previewTemplate.content?.basic?.descriptionTemplate || '未设置' }}</p>
            </el-tab-pane>
            <el-tab-pane label="触发条件">
              <div v-if="previewTemplate.content?.triggers?.length">
                <div v-for="(condition, index) in previewTemplate.content.triggers" :key="index"
                  class="condition-preview">
                  <p>条件 {{ index + 1 }}：{{ condition.parameter }} {{ condition.operator }} {{ condition.value }} {{
                    condition.unit }}</p>
                </div>
              </div>
              <p v-else>暂无触发条件</p>
            </el-tab-pane>
            <el-tab-pane label="执行步骤">
              <div v-if="previewTemplate.content?.steps?.length">
                <div v-for="(step, index) in previewTemplate.content.steps" :key="index" class="step-preview">
                  <h5>步骤 {{ index + 1 }}：{{ step.name }}</h5>
                  <p><strong>类型：</strong>{{ step.type }}</p>
                  <p><strong>负责人：</strong>{{ step.responsible }}</p>
                  <p><strong>描述：</strong>{{ step.description }}</p>
                </div>
              </div>
              <p v-else>暂无执行步骤</p>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewVisible = false">关闭</el-button>
          <el-button type="success" @click="useTemplate(previewTemplate)">
            使用此模板
          </el-button>
        </div>
      </template>
    </el-dialog>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Delete,
  Search,
  Refresh,
  Document,
  Umbrella,
  Sunny,
  Setting
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'template-selected', template: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false
})

const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 模板数据
const templates = ref([
  {
    id: 1,
    name: '标准防洪应急预案模板',
    type: 'flood',
    version: 'v2.1',
    usageCount: 25,
    creator: '系统管理员',
    createTime: '2024-01-01 10:00:00',
    description: '适用于一般防洪应急情况的标准预案模板',
    isOfficial: true,
    tags: ['标准', '防洪', '应急'],
    content: {
      basic: {
        nameTemplate: '{区域}防洪应急预案',
        priority: 'high',
        descriptionTemplate: '针对{区域}的防洪应急处置预案'
      },
      triggers: [
        { parameter: 'water-level', operator: 'gt', value: '警戒水位', unit: 'm' }
      ],
      steps: [
        { name: '启动预警', type: 'notification', responsible: '值班员', description: '发布预警信息' }
      ],
      personnel: {
        notification: ['duty-officer', 'dispatcher'],
        execution: ['operator', 'emergency-team']
      }
    }
  },
  {
    id: 2,
    name: '抗旱应急预案模板',
    type: 'drought',
    version: 'v1.5',
    usageCount: 18,
    creator: '张三',
    createTime: '2024-01-05 14:30:00',
    description: '适用于干旱期间的水资源调度预案模板',
    isOfficial: false,
    tags: ['抗旱', '水资源', '调度'],
    content: {
      basic: {
        nameTemplate: '{区域}抗旱应急预案',
        priority: 'medium',
        descriptionTemplate: '针对{区域}干旱情况的应急处置预案'
      },
      triggers: [
        { parameter: 'rainfall', operator: 'lt', value: '50', unit: 'mm' }
      ],
      steps: [
        { name: '评估旱情', type: 'check', responsible: '技术员', description: '评估当前旱情等级' }
      ],
      personnel: {
        notification: ['technician', 'manager'],
        execution: ['operator', 'maintainer']
      }
    }
  },
  {
    id: 3,
    name: '供水应急预案模板',
    type: 'water-supply',
    version: 'v1.8',
    usageCount: 32,
    creator: '李四',
    createTime: '2024-01-10 09:15:00',
    description: '供水系统故障或污染事件的应急处置模板',
    isOfficial: true,
    tags: ['供水', '故障', '污染'],
    content: {
      basic: {
        nameTemplate: '{设施}供水应急预案',
        priority: 'urgent',
        descriptionTemplate: '针对{设施}供水异常的应急处置预案'
      },
      triggers: [
        { parameter: 'water-quality', operator: 'lt', value: '标准值', unit: '' }
      ],
      steps: [
        { name: '停止供水', type: 'operation', responsible: '操作员', description: '立即停止受影响区域供水' }
      ],
      personnel: {
        notification: ['duty-officer', 'manager'],
        execution: ['operator', 'safety-officer']
      }
    }
  }
])

// 搜索和筛选
const searchKeyword = ref('')
const activeCategory = ref('all')
const selectedTemplates = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 模板表单相关
const templateFormVisible = ref(false)
const isEditMode = ref(false)
const saveTemplateLoading = ref(false)
const templateFormRef = ref()
const templateForm = ref({
  name: '',
  type: '',
  version: '',
  scope: '',
  description: '',
  tags: [],
  content: {
    basic: {
      nameTemplate: '',
      priority: '',
      descriptionTemplate: ''
    },
    triggers: [],
    steps: [],
    personnel: {
      notification: [],
      execution: []
    }
  }
})

const templateFormRules = {
  name: [
    { required: true, message: '请输入模板名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  version: [
    { required: true, message: '请输入版本号', trigger: 'blur' }
  ],
  scope: [
    { required: true, message: '请选择适用范围', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入模板描述', trigger: 'blur' }
  ]
}

// 标签输入相关
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInputRef = ref()

// 内容编辑相关
const contentTab = ref('basic')

// 预览相关
const previewVisible = ref(false)
const previewTemplateData = ref(null)

// 计算属性
const filteredTemplates = computed(() => {
  let filtered = templates.value
  
  // 按分类筛选
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(template => template.type === activeCategory.value)
  }
  
  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(keyword) ||
      template.description.toLowerCase().includes(keyword) ||
      getTypeText(template.type).toLowerCase().includes(keyword) ||
      template.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }
  
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const totalFilteredTemplates = computed(() => {
  let filtered = templates.value
  
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(template => template.type === activeCategory.value)
  }
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(template =>
      template.name.toLowerCase().includes(keyword) ||
      template.description.toLowerCase().includes(keyword) ||
      getTypeText(template.type).toLowerCase().includes(keyword) ||
      template.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }
  
  return filtered.length
})

const totalTemplates = computed(() => templates.value.length)

// 获取指定类型的模板数量
const getTemplateCountByType = (type: string) => {
  return templates.value.filter(template => template.type === type).length
}

// 获取模板图标
const getTemplateIcon = (type: string) => {
  const iconMap = {
    'flood': Umbrella,
    'drought': Sunny,
    'water-supply': WaterDrop,
    'safety': Shield,
    'custom': Setting
  }
  return iconMap[type] || Document
}

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'flood': 'primary',
    'drought': 'warning',
    'water-supply': 'success',
    'safety': 'danger',
    'custom': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const textMap = {
    'flood': '防洪预案',
    'drought': '抗旱预案',
    'water-supply': '供水预案',
    'safety': '安全预案',
    'custom': '自定义'
  }
  return textMap[type] || type
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedTemplates.value = selection
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

// 分类切换
const handleCategoryChange = (category: string) => {
  activeCategory.value = category
  currentPage.value = 1
}

// 刷新模板列表
const refreshTemplates = () => {
  ElMessage.success('模板列表已刷新')
}

// 显示创建模板对话框
const showCreateTemplateDialog = () => {
  isEditMode.value = false
  templateForm.value = {
    name: '',
    type: '',
    version: 'v1.0',
    scope: 'global',
    description: '',
    tags: [],
    content: {
      basic: {
        nameTemplate: '',
        priority: 'medium',
        descriptionTemplate: ''
      },
      triggers: [],
      steps: [],
      personnel: {
        notification: [],
        execution: []
      }
    }
  }
  templateFormVisible.value = true
}

// 编辑模板
const editTemplate = (template: any) => {
  isEditMode.value = true
  templateForm.value = JSON.parse(JSON.stringify(template))
  templateFormVisible.value = true
}

// 保存模板
const handleSaveTemplate = async () => {
  try {
    await templateFormRef.value.validate()
    
    saveTemplateLoading.value = true
    
    // 模拟保存API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEditMode.value) {
      const index = templates.value.findIndex(t => t.id === templateForm.value.id)
      if (index > -1) {
        templates.value[index] = { ...templateForm.value }
      }
      ElMessage.success('模板更新成功')
    } else {
      const newTemplate = {
        ...templateForm.value,
        id: Date.now(),
        usageCount: 0,
        creator: '当前用户',
        createTime: new Date().toISOString(),
        isOfficial: false
      }
      templates.value.unshift(newTemplate)
      ElMessage.success('模板创建成功')
    }
    
    templateFormVisible.value = false
    
  } catch (error) {
    ElMessage.error('表单验证失败')
  } finally {
    saveTemplateLoading.value = false
  }
}

// 预览模板
const previewTemplate = (template: any) => {
  previewTemplateData.value = template
  previewVisible.value = true
}

// 使用模板
const useTemplate = (template: any) => {
  emit('template-selected', template)
  ElMessage.success(`已选择模板：${template.name}`)
  dialogVisible.value = false
}

// 复制模板
const copyTemplate = (template: any) => {
  const newTemplate = {
    ...JSON.parse(JSON.stringify(template)),
    id: Date.now(),
    name: `${template.name} - 副本`,
    usageCount: 0,
    creator: '当前用户',
    createTime: new Date().toISOString(),
    isOfficial: false
  }
  
  templates.value.unshift(newTemplate)
  ElMessage.success('模板复制成功')
}

// 删除模板
const deleteTemplate = async (template: any) => {
  try {
    await ElMessageBox.confirm(`确认删除模板"${template.name}"？`, '确认删除', {
      type: 'warning'
    })
    
    const index = templates.value.findIndex(t => t.id === template.id)
    if (index > -1) {
      templates.value.splice(index, 1)
    }
    
    ElMessage.success('模板删除成功')
    
  } catch {
    // 用户取消
  }
}

// 批量删除模板
const deleteSelectedTemplates = async () => {
  if (selectedTemplates.value.length === 0) {
    ElMessage.warning('请选择要删除的模板')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedTemplates.value.length} 个模板？`, '确认删除', {
      type: 'warning'
    })
    
    selectedTemplates.value.forEach(template => {
      const index = templates.value.findIndex(t => t.id === template.id)
      if (index > -1) {
        templates.value.splice(index, 1)
      }
    })
    
    selectedTemplates.value = []
    ElMessage.success('批量删除成功')
    
  } catch {
    // 用户取消
  }
}

// 导出选中模板
const exportSelectedTemplates = () => {
  if (selectedTemplates.value.length === 0) {
    ElMessage.warning('请选择要导出的模板')
    return
  }
  
  ElMessage.success(`导出 ${selectedTemplates.value.length} 个模板功能开发中...`)
}

// 导入模板
const importTemplate = () => {
  ElMessage.info('导入模板功能开发中...')
}

// 标签管理
const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInputRef.value?.focus()
  })
}

const addTag = () => {
  if (tagInputValue.value && !templateForm.value.tags.includes(tagInputValue.value)) {
    templateForm.value.tags.push(tagInputValue.value)
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

const removeTag = (tag: string) => {
  const index = templateForm.value.tags.indexOf(tag)
  if (index > -1) {
    templateForm.value.tags.splice(index, 1)
  }
}

// 触发条件管理
const addTriggerCondition = () => {
  templateForm.value.content.triggers.push({
    parameter: '',
    operator: '',
    value: '',
    unit: ''
  })
}

const removeTriggerCondition = (index: number) => {
  templateForm.value.content.triggers.splice(index, 1)
}

// 执行步骤管理
const addExecutionStep = () => {
  templateForm.value.content.steps.push({
    name: '',
    type: '',
    responsible: '',
    description: ''
  })
}

const removeExecutionStep = (index: number) => {
  templateForm.value.content.steps.splice(index, 1)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.template-manage {
  max-height: 70vh;
  overflow-y: auto;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.left-actions,
.right-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.template-categories {
  margin-bottom: 20px;
}

.template-list {
  background-color: white;
  border-radius: 8px;
}

.template-name {
  display: flex;
  align-items: center;
}

.template-icon {
  margin-right: 8px;
  color: #409eff;
}

.usage-count {
  color: #666;
  font-size: 14px;
}

.description-text {
  color: #666;
  font-size: 14px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.template-content-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.trigger-conditions,
.execution-steps {
  padding: 10px 0;
}

.condition-item,
.step-item {
  margin-top: 15px;
}

.template-preview {
  padding: 20px 0;
}

.preview-content {
  margin-top: 20px;
}

.preview-content h4 {
  margin-bottom: 15px;
  color: #333;
}

.condition-preview,
.step-preview {
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 10px;
}

.step-preview h5 {
  margin: 0 0 8px 0;
  color: #333;
}

.step-preview p {
  margin: 4px 0;
  color: #666;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs--border-card) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

:deep(.el-tab-pane) {
  padding: 20px;
}

:deep(.el-card) {
  margin-bottom: 10px;
}

:deep(.el-card__body) {
  padding: 15px;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}
</style>